﻿using SqlSugar;
using SqlSugar_Geometry_Model.Entity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace SqlSugar_Geometry_Model
{
    public class DbHelper
    {
        private SqlSugarClient Db;
        //Data Source              数据库所在服务器IP地址和端口号
        //Initial Catalog          数据库名称
        //Persist Security Info    连接成功后是否保存密码信息
        //User ID                  数据库登录用户名
        //Password                 数据库登录密码
        //MultipleActiveResultSets 允许数据库复用
        public string DbConn = @"Data Source=9865mz1425az.vicp.fun,13755;Initial Catalog=TestDb;Persist Security Info=True;User ID=sa;Password=Nap650;MultipleActiveResultSets=True";

        /// <summary>
        /// 获取SqlSugar Db
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetDb()
        {
            Db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = DbConn,
                DbType = DbType.SqlServer,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true
            },
            Db =>
            {
                //配置
            });
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Debug.WriteLine("sql语句:\r\n" + sql + "\r\n");
            };
            return Db;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public void CreateDataBase()
        {

            using (SqlSugarClient db = GetDb())
            {
                db.DbMaintenance.CreateDatabase();   //创建数据库
                List<String> dbs = db.DbMaintenance.GetDataBaseList();  //获取所有数据库名称
                if (dbs.Exists(s => s != "TestDb"))   //判断数据库是否存在
                {
                    Debug.WriteLine("数据库存在！");
                    //var tbs = db.DbMaintenance.GetTableInfoList(true);   //获取数据库下所有表
                    //db.DbMaintenance.DropTable(typeof(Test));   //  删除Test
                }
                //创建表
                db.CodeFirst.InitTables(
                    typeof(Test)
                 );
            }
        }
    }
}